//
//  ST_JoinRoomOptionsController.swift
//  btvideo
//
//  Created by mac on 2021/5/8.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SwiftyAttributes

class ST_JoinRoomOptionsController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .clear
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            make.height.equalTo(467+BTSafeAreaBottom+16)
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.top.right.left.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        
        root_view.addSubview(info_title_label)
        info_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(61)
            make.height.equalTo(18)
        }
        
        
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(info_title_label.snp.bottom).offset(12)
            make.left.right.equalToSuperview()
            make.height.equalTo(44+12+44)
        }
        
        
        root_view.addSubview(second_title_label)
        second_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(collectionView.snp.bottom).offset(24)
            make.height.equalTo(18)
        }
        
        root_view.addSubview(video_choice_btn)
        video_choice_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(second_title_label.snp.bottom).offset(15)
            make.width.equalTo(113)
            make.height.equalTo(50)
        }
        
        root_view.addSubview(voice_choice_btn)
        voice_choice_btn.snp.makeConstraints { (make) in
            make.left.equalTo(video_choice_btn.snp.right).offset(8)
            make.width.height.centerY.equalTo(video_choice_btn)
        }
        
        root_view.addSubview(create_btn)
        create_btn.snp.makeConstraints { (make) in
            make.width.equalTo(345)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-81+34-BTSafeAreaBottom)
        }
        
        
        
        root_view.addSubview(notice_btn)
        notice_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(create_btn.snp.bottom).offset(5)
            make.height.equalTo(16)
        }
        
        
        request_data()
    }
    
    fileprivate func request_data(){
        
        
        JVrequest(PH.roomThemeConfigApi,parameters: ["theme_type":2]) { (json) in
            
            self.data_array = json["data"].arrayValue.map({ ST_LiveBeautyHeaderModel(fromJson: $0) })
            
            self.data_array.first?.isSelected = true
            
            if self.data_array.first != nil{
                self.last_selected_index = 0
            }
            
            self.collectionView.reloadData()
            
        } failure: { (code, error) in
            
            self.toast(text: error)
        }
        
    }
    
    // MARK: - Properties
    fileprivate lazy var close_view:UIControl = {
        let control = UIControl()
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        control.cornerRadius = 16
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "房间信息"
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var info_title_label:UILabel = {
        let l = UILabel()
        l.text = "选择一个房间主题"
        l.textColor = #colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)
        l.font = .systemFont(ofSize: 13, weight: .medium)
        return l
    }()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        //        controlLayout.scrollDirection = .horizontal
        controlLayout.minimumLineSpacing = 10
        controlLayout.minimumInteritemSpacing = 10
        
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 15)
        
        controlLayout.itemSize = CGSize.init(width: (ScreenWidth - 20 - 16*2)/3.0, height: 44)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_JoinRoomOptionsCell.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.clear
        //        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    fileprivate lazy var second_title_label:UILabel = {
        let control = UILabel.init()
        control.text = "选择一种通话方式"
        control.textColor = UIColor.init(hex: 0xAAAAAA)
        control.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var chooseBtb = video_choice_btn
    
    private let choose_btn_border_color = UIColor(hex: 0xFEC207)

    private let choose_btn_background_color = UIColor(hex: 0xFEC207, transparency: 0.12)

    
    private let normal_btn_border_color = UIColor(hex: 0xF3F3F3)
    
    private let normal_btn_background_color = UIColor(hex: 0xF3F3F3)
    
    
    fileprivate lazy var video_choice_btn:UIButton = {
        let control = UIButton()
        control.isSelected = true
        control.setTitle("视频通话", for: .normal)
        control.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        control.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        control.borderColor = choose_btn_border_color
        control.backgroundColor = choose_btn_background_color
        control.borderWidth = 2
        control.cornerRadius = 25
        
        
//        control.setBackgroundImage(ST_ImageUtils.imageName("room_video_choice_icon"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(chooseHandle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var voice_choice_btn:UIButton = {
        let control = UIButton()
        control.setTitle("语音通话", for: .normal)
        control.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        control.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        
        control.backgroundColor = normal_btn_background_color
        control.cornerRadius = 25
        
//        control.setBackgroundImage(ST_ImageUtils.imageName("room_voice_choice_icon"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(chooseHandle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    
    fileprivate lazy var create_btn:UIButton = {
        
        let control = UIButton(type: .custom)
        control.backgroundColor = UIColor(hex: 0xFEC207)
        control.cornerRadius = 44/2.0
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        control.setTitleForAllStates("创建房间")
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(createHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var notice_btn:ST_TianButton = {
        
        let control = ST_TianButton(style: .title_left_image_right(titleLeft: 0, imageSize: CGSize(width: 16, height: 16), layout: ST_TianButtonLayoutModel.inside_auto_resize(relevantOffset: 4, lastControlEdgeValue: 1)))
        
        let str =  SCComponets.rich_text_storage_component.json["up_live_rank"]["content"].stringValue.withAttributes([.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x5F95D8)!)])
        
        control.setTitle(str, for: .normal)
        control.setImage(ST_ImageUtils.imageName("why_green_icon"), for: .normal)
        control.addTarget(self, action: #selector(notice_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var last_selected_index:Int?
    
    fileprivate var data_array = [ST_LiveBeautyHeaderModel]()
    
}

//MARK: - Event
extension ST_JoinRoomOptionsController{
    
    @objc fileprivate func close_handle(){
        
        goback_previous_controller()
        
    }
    
    
    
    @objc fileprivate func createHandle(){
        
        ST_BTUserInfoManager.shared.judge_account_frozen().withUnretained(self).subscribe(onNext: { own,_ in
            
            own.push_create_room()
            
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    private func push_create_room(){
        
        guard let index = last_selected_index,let model = data_array[safe: index],create_btn.alpha > 0.9 else{return}
        
        let isVideo = chooseBtb == video_choice_btn
        
        let themeId = model.id
        
        let upLiveExecute = {
            
            self.goback_previous_controller(animated: true) {
                
                ST_LiveBeautyWidget.shared.settingUpLiveSquare(isVideo: isVideo, fromController: ST_BTBootController.shared,themeId:themeId,sign: "").subscribe(onNext: { f in
                    
                    if !f { return }
                    
                    let alertView = ST_BTHUDAlert.init(noticeText: "创建成功", imageName: "create_room_success")
                    
                    ST_BTLaunchController.shared.view.addSubview(alertView)
                    alertView.snp.makeConstraints { (make) in
                        make.edges.equalToSuperview()
                    }
                    
                }).disposed(by: ST_BTLaunchController.shared.rx.disposeBag)
             
            }
        }
        
        if isVideo{
            
            ST_MediaChatDispatcher.shared.request_audio_permission_with_execute {
                
                ST_MediaChatDispatcher.shared.request_video_permission_with_execute {
                    
                    upLiveExecute()
                }
            }
        }else{
            
            ST_MediaChatDispatcher.shared.request_audio_permission_with_execute {
                upLiveExecute()
            }
        }
        
    }
    
    @objc fileprivate func chooseHandle(sender:UIButton){
        
        if sender.isSelected{return}
        
        chooseBtb.isSelected = false
        chooseBtb.borderColor = .clear
        chooseBtb.borderWidth = 0
        chooseBtb.backgroundColor = normal_btn_background_color
        
        sender.isSelected = true
        chooseBtb = sender
        chooseBtb.borderColor = choose_btn_border_color
        chooseBtb.borderWidth = 2
        chooseBtb.backgroundColor = choose_btn_background_color
        
    }
    
    
    @objc fileprivate func notice_handle(){
        
        let alert = ST_RiseLiveValueAlertController()
        
        alert.overCurrentContext = true
        
        alert.over_current_context_alpha = "0.4"
        
        GlobalPresent(toController: alert)
        
    }
    
}

//MARK: - Delegate
extension ST_JoinRoomOptionsController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_JoinRoomOptionsCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.row]
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if let last = last_selected_index{
            data_array[safe: last]?.isSelected = false
        }
        
        data_array[safe: indexPath.row]?.isSelected = true
        
        last_selected_index = indexPath.row
        
        collectionView.reloadData()
        
    }
    
}


//MARK: - UItextField Delegate
extension ST_JoinRoomOptionsController:UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard var animal = textField.text else{
            
            create_btn.alpha = 0.5
            
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: string)
            
            create_btn.alpha = animal.count > 2 ? 1 : 0.5
            
            return animal.count <= 15
            
        }else{
            return true
        }
    }
    
}



//MARK: - Cell
class ST_JoinRoomOptionsCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        contentView.addSubview(coverView)
        coverView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        coverView.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { make in
            make.width.height.equalTo(36)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(15)
        }
        
        coverView.addSubview(nameLabel)
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(cover_image_view.snp.right).offset(5)
            make.centerY.equalToSuperview()
        }
        
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private let cover_view_normal_background_color = UIColor(hex: 0xF3F3F3)
    
    private let cover_view_selected_background_color = UIColor(hex: 0xFEC207, transparency: 0.12)
    
    fileprivate lazy var coverView:UIView = {
        let control = UIView()
        control.cornerRadius = 22
        control.borderWidth = 2
        control.borderColor = cover_view_normal_background_color
        control.backgroundColor = cover_view_normal_background_color
        return control
    }()
    
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        return control
    }()
    
    fileprivate lazy var nameLabel:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        l.font = .systemFont(ofSize: 14, weight: .medium)
        return l
    }()
    
    weak var model:ST_LiveBeautyHeaderModel?{
        didSet{
            
            
            guard let m = model else { return  }
            
//            self.cover_image_view.sd_setImage(with: m.midImage.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            cover_image_view.sd_setImage(with: m.bigImage.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            nameLabel.text = m.name
            
            if m.isSelected{
                self.coverView.borderColor = UIColor(hex: 0xFEC207)
                self.coverView.backgroundColor = cover_view_selected_background_color
            }else{
                self.coverView.borderColor = cover_view_normal_background_color
                self.coverView.backgroundColor = cover_view_normal_background_color
            }
        }
    }
    
//    weak var roomModel:VoiceChatRoomTheme?{
//        didSet{
//
//
//            guard let m = roomModel else { return  }
//
//            self.cover_image_view.sd_setImage(with: m.img.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
//
//            if m.isSelected{
//                self.cover_image_view.borderColor = UIColor(hex: 0x4A4A4A)
//            }else{
//                self.cover_image_view.borderColor = .clear
//            }
//        }
//    }
    
    
}
